// TcpModule.h
#include "Module.h"
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#include "TcpModule.h"
TcpModule::TcpModule(std::string addr, int port) : m_port(port)
{
    init();
}
TcpModule::~TcpModule()
{
    delete client;
}
void TcpClientModule::read_message()
{
    uint8_t temp_buffer[1024] = {0};
    int len = read(m_channel->getfd(), temp_buffer, 1024);
    if (len > 0)
    {
        m_read_buffer.write(temp_buffer, len);
        if (readCallback_)
        {
            if (threadProc)
            {
                m_woker_pool->addTask(Task(readCallback_,&m_read_buffer));
            }
            readCallback_(&m_read_buffer);
        }
    }
    else
    {
        disable();
    }
}
void TcpModule::init()
{
    // 初始化 TCP 套接字并绑定
    std::cout << "Initializing TCP Module..." << std::endl;

    m_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (m_fd == -1)
    {
        perror("Socket creation failed");
        return;
    }

    // 设置端口复用
    int reuse = 1;
    if (setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &reuse, sizeof(reuse)) == -1)
    {
        perror("Setsockopt failed");
        close(m_fd);
        return;
    }

    // 设置服务器地址
    sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY; // 监听所有网卡
    server_addr.sin_port = htons(m_port);     // 绑定端口（注意：这里应该使用成员变量 port_ 而不是未定义的 port）

    // 绑定套接字
    if (bind(m_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("Bind failed");
        close(m_fd);
        return;
    }

    // 设置监听
    if (listen(m_fd, 5) == -1) // 设置最大等待连接数为 5
    {
        perror("Listen failed");
        close(m_fd);
        return;
    }
    open_read();
    std::cout << "Server started, listening on port " << m_port << "..." << std::endl;
}

void TcpModule::read_message()
{
    printf("have new connction %d\n", m_fd);
    if (m_fd == -1)
    {
        std::cout << "Server is not initialized!" << std::endl;
    }

    // 接受客户端连接
    sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    int fd = accept(m_fd, (struct sockaddr *)&client_addr, &client_len);
    printf("new con fd=%d\n", fd);
    client = new TcpClientModule(fd);
    client->set_read_callback(client_cb);
    client->open_read();
}
